<script setup lang="ts">
import { onMounted, ref, reactive, watch, h } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import DynamicForm from "@/components/DynamicForm/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElTag } from "element-plus";
import { searchAllRecords } from "../servers";

interface Props {
  configName?: string;
  task?: string;
}

const props = withDefaults(defineProps<Props>(), {
  configName: "default",
  task: "",
});

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const allRecords = ref<any[]>([]);
const loading = ref(false);
const searchFormRef = ref<DynamicFormInstance>();

// 统计数据
const statistics = ref({
  dns_count: 0,
  http_count: 0,
  total: 0,
});

// 搜索表单
const searchForm = reactive({
  keyword: "",
  type: "all",
});

const searchConfig: FormItemConfig[] = [
  {
    key: "keyword",
    name: "关键词",
    type: "input",
    placeholder: "搜索关键词（必填）",
    col: {
      span: 6,
    },
    params: {
      clearable: true,
    },
  },
  {
    key: "type",
    name: "类型",
    type: "select",
    placeholder: "选择类型",
    options: [
      { label: "全部", value: "all" },
      { label: "DNS", value: "dns" },
      { label: "HTTP", value: "http" },
    ],
    params: {
      clearable: false,
      style: { width: "150px" },
    },
  },
];

const columns = ref<TableColumn[]>([
  {
    label: "类型",
    prop: "record_type",
    width: 80,
    show: true,
    render: (row) => {
      const type = row.record_type || "unknown";
      const typeMap: Record<
        string,
        { text: string; type: "success" | "warning" | "info" | "danger" }
      > = {
        dns: { text: "DNS", type: "success" },
        http: { text: "HTTP", type: "warning" },
      };
      const item = typeMap[type] || { text: type, type: "info" as const };
      return h(ElTag, { type: item.type, size: "small" }, () => item.text);
    },
  },
  {
    label: "ID",
    prop: "id",
    show: true,
  },
  {
    label: "域名",
    prop: "name",
    show: true,
  },
  {
    label: "远程地址",
    prop: "remote_addr",
    show: true,
  },
  {
    label: "请求",
    prop: "request",
    minWidth: 200,
    show: true,
  },
  {
    label: "User-Agent",
    prop: "user_agent",
    minWidth: 200,
    show: true,
  },
  {
    label: "时间",
    prop: "time",
    width: 180,
    show: true,
  },
]);

// 获取全部记录列表
const fetchAllRecords = async () => {
  if (!props.configName) return;

  if (!searchForm.keyword) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }

  loading.value = true;
  try {
    const params: any = {
      config_name: props.configName,
      keyword: searchForm.keyword,
      type: searchForm.type,
      page: pagination.currentPage,
      page_size: pagination.pageSize,
    };

    const { data } = await searchAllRecords(params);

    // 合并 DNS 和 HTTP 记录，并添加类型标识
    const dnsRecords = (data.dns_records || []).map((record: any) => ({
      ...record,
      record_type: "dns",
    }));
    const httpRecords = (data.http_records || []).map((record: any) => ({
      ...record,
      record_type: "http",
    }));

    allRecords.value = [...dnsRecords, ...httpRecords];
    pagination.total = data.total || 0;
    statistics.value = {
      dns_count: data.dns_count || 0,
      http_count: data.http_count || 0,
      total: data.total || 0,
    };
  } catch (error: any) {
    console.error("搜索记录失败:", error);
    ElMessage.error(error.message || "搜索记录失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = (value: any) => {
  searchForm.keyword = value.keyword || "";
  searchForm.type = value.type || "all";
  pagination.currentPage = 1;
  fetchAllRecords();
};

const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  searchForm.keyword = "";
  searchForm.type = "all";
  pagination.currentPage = 1;
  allRecords.value = [];
  pagination.total = 0;
  statistics.value = {
    dns_count: 0,
    http_count: 0,
    total: 0,
  };
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchAllRecords();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchAllRecords();
};

// 监听配置变化
watch(
  () => props.configName,
  () => {
    pagination.currentPage = 1;
    if (searchForm.keyword) {
      fetchAllRecords();
    }
  }
);

onMounted(() => {
  // 不自动加载，需要用户输入关键词后搜索
});
</script>

<template>
  <div>
    <el-card shadow="never">
      <div class="search-form-container">
        <DynamicForm
          ref="searchFormRef"
          v-model="searchForm"
          :form-config="searchConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleSearchReset"
        />
      </div>
      <div v-if="statistics.total > 0" class="statistics-info">
        <el-tag type="info">DNS: {{ statistics.dns_count }} 条</el-tag>
        <el-tag type="warning">HTTP: {{ statistics.http_count }} 条</el-tag>
        <el-tag type="success">总计: {{ statistics.total }} 条</el-tag>
      </div>
    </el-card>

    <div style="height: 10px"></div>

    <el-card>
      <DynamicTable
        :pagination="pagination"
        :columns="columns"
        :data="allRecords"
        :loading="loading"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.search-form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.statistics-info {
  display: flex;
  gap: 12px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}
</style>
